﻿// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
    "use strict";

    WinJS.Binding.optimizeBindingReferences = true;

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;
    var canvas, context;
    var gameStage;
    var preload;
    var scaleW = window.innerWidth / 1366;
    var scaleH = window.innerHeight / 768;

    var logoScreenImage, logoScreenBitmap;
    var player, powerup;
    var spaceImage, spaceBitmap;
    var playerIdleImage, playerIdleBitmap;
    var dustImage, dustBitmap;
    var freezeImage;
    var bombImage;
    var reverseImage;
    var aimplayerImage;
    var dustsmallerImage;
    var pauseImage;
    var ufosmallerImage;
    var powerupBitmap;
    var powerupicon;

    var newGame = true;
    var isGameOver = false;

    var dusts = [];
    var scoreText;
    var freezeText;
    var notaimText;
    var dustsmallerText;
    var ufosmallerText;
    var timeToAddNewDust = 0;
    var playerScore = 0;
    var countscore = 0;
    var poweruptime;
    var poweruptime2;
    var poweruptime3;
    var freezeperiod = false;
    var dustsmallerperiod = false;
    var ufosmallerperiod = false;
    var powerupmode = 0;
    var poweruptype = 0;
    var notaimplayer = -100;
    var newdustfrequency;
    var nownotaim;
    var countdown;
    var dustpowerupsize;
    var ufopowerupsize=1;
    var dustSpeed;

    var freezespeed = 1;

    var addnewpowerup = true;
    var havepowerup = false;

    //CHANGEABLE ZONE (You can modify these variable to set difficulty)
    //
    //
    var dustSpeedModify = 2.5;           // limit to 0 - infinity   // standard = 2.5
    var newdustfrequency_modify = 1000;  // 1 - infinity            // standard = 1000
    var aimatplayer = 50;       // (0-100)%                // standard = 50
    var notaimplayerperiod = 5;
    var powerup_freeze_percent = 10;
    var powerup_bomb_percent = 3;
    var powerup_reverse_percent = 12;
    var powerup_aimplayer_percent = 5;
    var powerup_dustsmaller_percent = 5;
    var powerup_ufosmaller_percent = 5;
    //
    //
    //END CHANGEABLE ZONE

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }
            args.setPromise(WinJS.UI.processAll());
        }
    };

    function initialize() {
        canvas = document.getElementById("gameCanvas");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        context = canvas.getContext("2d");
        canvas.addEventListener("MSPointerUp", pointerUp, false);
        canvas.addEventListener("MSPointerMove", pointerMove, false);
        
        gameStage = new createjs.Stage(canvas);
        
        loadContent();
    }
    
    function loadContent() {
        preload = new createjs.PreloadJS();
        preload.onComplete = prepareStage;

        var manifest = [
            { id: "logoScreen", src: "images/GFX/Logo.jpg" },
            { id: "space", src: "images/GFX/space.jpg" },
            { id: "dust", src: "images/GFX/dust.png" },
            { id: "powerup_freeze", src: "images/GFX/Freeze.png" },
            { id: "powerup_bomb", src: "images/GFX/Bomb.png" },
            { id: "powerup_reverse", src: "images/GFX/Reverse.png" },
            { id: "powerup_aimplayer", src: "images/GFX/Aimplayer.png" },
            { id: "powerup_dustsmaller", src: "images/GFX/DustSmaller.png" },
            { id: "powerup_pause", src: "images/GFX/Pause.png" },
            { id: "powerup_ufosmaller", src: "images/GFX/UFOSmaller.png" },
            { id: "playerIdle", src: "images/GFX/UFO.png" }
        ];

        preload.loadManifest(manifest);
        if (newdustfrequency < 1) newdustfrequency = 500;
        if (dustSpeed <= 0) dustSpeed = 2;
    }

    function prepareStage() {
        logoScreenImage = preload.getResult("logoScreen").result;
        logoScreenBitmap = new createjs.Bitmap(logoScreenImage);
        logoScreenBitmap.scaleX = scaleW;
        logoScreenBitmap.scaleY = scaleH;
        gameStage.addChild(logoScreenBitmap);

        spaceImage = preload.getResult("space").result;
        spaceBitmap = new createjs.Bitmap(spaceImage);
        spaceBitmap.visible = false;
        spaceBitmap.scaleX = scaleW;
        spaceBitmap.scaleY = scaleH;
        gameStage.addChild(spaceBitmap);
        
        playerIdleImage = preload.getResult("playerIdle").result;
        playerIdleBitmap = new createjs.Bitmap(playerIdleImage);
        playerIdleBitmap.visible = false;
        playerIdleBitmap.scaleX = scaleW;
        playerIdleBitmap.scaleY = scaleH;
        gameStage.addChild(playerIdleBitmap);

        dustImage = preload.getResult("dust").result

        freezeImage = preload.getResult("powerup_freeze").result
        bombImage = preload.getResult("powerup_bomb").result
        reverseImage = preload.getResult("powerup_reverse").result
        aimplayerImage = preload.getResult("powerup_aimplayer").result
        dustsmallerImage = preload.getResult("powerup_dustsmaller").result
        pauseImage = preload.getResult("powerup_pause").result
        ufosmallerImage = preload.getResult("powerup_ufosmaller").result

        scoreText = new createjs.Text("Score: " + playerScore, "50px sans-serif", "yellow");
        scoreText.x = 30 * scaleW;
        scoreText.scaleX = scaleW;
        scoreText.scaleY = scaleH;
        scoreText.y = 30 * scaleH;
        scoreText.visible = false;
        gameStage.addChild(scoreText);

        freezeText = new createjs.Text("Freezing: " + Math.floor(poweruptime/300), "30px sans-serif", "cyan");
        freezeText.x = 30 * scaleW;
        freezeText.scaleX = scaleW;
        freezeText.scaleY = scaleH;
        freezeText.y = 100 * scaleH;
        freezeText.visible = false;
        gameStage.addChild(freezeText);

        notaimText = new createjs.Text("No Diagonal: " + notaimplayer + notaimplayerperiod - dusts.length, "30px sans-serif", "cyan");
        notaimText.x = 30 * scaleW;
        notaimText.scaleX = scaleW;
        notaimText.scaleY = scaleH;
        notaimText.y = 150 * scaleH;
        notaimText.visible = false;
        gameStage.addChild(notaimText);

        dustsmallerText = new createjs.Text("Dust Small: " + Math.floor(poweruptime2 / 300), "30px sans-serif", "cyan");
        dustsmallerText.x = 30 * scaleW;
        dustsmallerText.scaleX = scaleW;
        dustsmallerText.scaleY = scaleH;
        dustsmallerText.y = 200 * scaleH;
        dustsmallerText.visible = false;
        gameStage.addChild(dustsmallerText);

        ufosmallerText = new createjs.Text("UFO Small: " + Math.floor(poweruptime3 / 300), "30px sans-serif", "cyan");
        ufosmallerText.x = 30 * scaleW;
        ufosmallerText.scaleX = scaleW;
        ufosmallerText.scaleY = scaleH;
        ufosmallerText.y = 250 * scaleH;
        ufosmallerText.visible = false;
        gameStage.addChild(ufosmallerText);

        createjs.Ticker.setInterval(window.requestAnimationFrame);
        createjs.Ticker.addListener(gameLoop);
        player = new Player();
    }

    function pointerUp(event) {
        if (newGame) {
            newGame = false;
            playerScore = 0;
            addnewpowerup = true;
            notaimplayer = -100;
            nownotaim = false;
            dustsmallerperiod = false;
            ufosmallerperiod = false;
            newdustfrequency = newdustfrequency_modify;
            freezespeed = 1;
            countscore = 0;
            poweruptime = 0;
            poweruptime2 = 0;
            poweruptime3 = 0;
            dustpowerupsize = 1;
            ufopowerupsize = 1;
            dustSpeed = dustSpeedModify;
            powerupmode = 0;
            player.setscale();
        }
        if (powerupmode > 0) {
            var count;
            switch(powerupmode){
                case 1:
                    freezespeed = freezespeed/10;
                    poweruptime = 1500;
                    freezeperiod = true;
                    freezeText.visible = true;
                    break;
                case 2:
                    for (count = dusts.length-1; count >= 0; count--) gameStage.removeChild(dusts[count].dustBitmap);
                    dusts.length = 0;
                    notaimplayer = -100;
                    nownotaim = false;
                    notaimText.visible = false;
                    newdustfrequency = Math.floor(newdustfrequency*0.75);
                    break;
                case 3:
                    for (count = dusts.length - 1; count >= 0; count--) dusts[count].reverse();
                    break;
                case 4:
                    notaimplayer = dusts.length;
                    notaimText.visible = true;
                    nownotaim = true;
                    break;
                case 5:
                    dustpowerupsize = 0.4;
                    dustSpeed = dustSpeedModify * 1.5;
                    poweruptime2 = 1500;
                    dustsmallerperiod = true;
                    dustsmallerText.visible = true;
                    for (var i = 0; i < dusts.length; i++) {
                        dusts[i].setscale();
                        dusts[i].setspeed(1.5);
                    }
                    break;
                case 6:
                    for (var i = 0; i < 2; i++) {
                        dusts.push(new Dust(new createjs.Bitmap(dustImage)));
                        dusts[dusts.length - 1].setscale();
                        dusts[dusts.length - 1].setStartPosition(player.positionX, player.positionY);
                        dusts[dusts.length - 1].dustBitmap.visible = true;
                        gameStage.addChild(dusts[dusts.length - 1].dustBitmap);
                    }
                    ufopowerupsize = 0.3;
                    player.setscale();
                    poweruptime3 = 1500;
                    ufosmallerperiod = true;
                    ufosmallerText.visible = true;
                    break;

            }
            gameStage.removeChild(powerupicon);
            powerupmode = 0;
        }
        player.targetX = event.x;
        player.targetY = event.y;
    }

    function pointerMove(event) {
        player.targetX = event.x;
        player.targetY = event.y;
    }

    function gameLoop() {
        update();
        draw();
    }

    function draw() {
        gameStage.update();
    }

    function Player() {

        this.setscale = function () {
            playerIdleBitmap.scaleX = scaleW * ufopowerupsize;
            playerIdleBitmap.scaleY = scaleH * ufopowerupsize;
        }

        this.positionX = window.innerWidth / 2;
        this.positionY = window.innerHeight / 2;
        
        this.targetX = this.positionX;
        this.targetY = this.positionY;
        
        this.width = playerIdleBitmap.image.width * scaleW * ufopowerupsize;
        this.height = playerIdleBitmap.image.height * scaleH * ufopowerupsize;
    }

    function Dust(gfx) {
        var speedX, speedY;
        this.setscale = function () {
            this.dustBitmap.scaleX = scaleW * dustpowerupsize;
            this.dustBitmap.scaleY = scaleH * dustpowerupsize;
        }
        this.setStartPosition = function (tX, tY) {
            var temp, x, y;
            temp = Math.floor(Math.random() * 4);
            x = Math.random() * (window.innerWidth + 2 * this.dustBitmap.image.width) - this.dustBitmap.image.width;
            y = Math.random() * (window.innerHeight + 2 * this.dustBitmap.image.height) - this.dustBitmap.image.height;
            switch (temp) {
                case 0:
                    this.positionX = x;
                    this.positionY = -this.dustBitmap.image.height;
                    speedX = 0;
                    speedY = dustSpeed;
                    break;
                case 1:
                    this.positionX = window.innerWidth + this.dustBitmap.image.width;
                    this.positionY = y;
                    speedX = -dustSpeed;
                    speedY = 0;
                    break;
                case 2:
                    this.positionX = x;
                    this.positionY = window.innerHeight + this.dustBitmap.image.height;
                    speedX = 0;
                    speedY = -dustSpeed;
                    break;
                case 3:
                    this.positionX = -this.dustBitmap.image.width;
                    this.positionY = y;
                    speedX = dustSpeed;
                    speedY = 0;
                    break;
            }
            var lengthX, lengthY;
            if (Math.random() < aimatplayer / 100 && dusts.length - notaimplayerperiod > notaimplayer) {
                lengthX = tX - this.positionX;
                lengthY = tY - this.positionY;
                speedX = dustSpeed * lengthX / Math.sqrt(Math.pow(lengthX, 2) + Math.pow(lengthY, 2));
                speedY = dustSpeed * lengthY / Math.sqrt(Math.pow(lengthX, 2) + Math.pow(lengthY, 2));
            }
        }

        this.setspeed = function (newspeed) {
            speedX = newspeed * speedX;
            speedY = newspeed * speedY;
        }
        
        
        this.move = function () {
            this.positionX += speedX * freezespeed;
            this.positionY += speedY * freezespeed;
        };

        this.reverse = function () {
            speedX = -speedX;
            speedY = -speedY;
        }

        this.isCollision = function (playerX, playerY, playerW, playerH) {
            var centerX = this.positionX + (this.dustBitmap.image.width * scaleW * dustpowerupsize / 2);
            var centerY = this.positionY + (this.dustBitmap.image.height * scaleH * dustpowerupsize / 2);
            
            if ((centerX >= playerX - playerW / 2) && (centerX < playerX + playerW / 2)) {
                if ((centerY >= playerY - playerH / 2) && (centerY < playerY + playerH / 2)) {
                    return true;
                }
            }
            
            return false;
        }
        this.dustBitmap = gfx;
    }

    function Powerup(pfx) {
        var speedX, speedY;
        this.setscale = function () {
            this.powerupBitmap.scaleX = scaleW;
            this.powerupBitmap.scaleY = scaleH;
        }
        this.setStartPosition = function () {
            var temp, x, y;
            temp = Math.floor(Math.random() * 4);
            x = Math.random() * (window.innerWidth - this.powerupBitmap.image.width);
            y = Math.random() * (window.innerHeight - this.powerupBitmap.image.height);
            switch (temp) {
                case 0:
                    this.positionX = x;
                    this.positionY = 0;
                    break;
                case 1:
                    this.positionX = window.innerWidth - this.powerupBitmap.image.width;
                    this.positionY = y;
                    break;
                case 2:
                    this.positionX = x;
                    this.positionY = window.innerHeight - this.powerupBitmap.image.height;
                    break;
                case 3:
                    this.positionX = 0;
                    this.positionY = y;
                    break;
            }
            speedX = 0.6;
            speedY = 0.6;
        }
        this.move = function () {
            this.positionX += speedX;
            this.positionY += speedY;
            if (this.positionX < 0 || this.positionX > window.innerWidth - this.powerupBitmap.image.width) speedX = -speedX;
            if (this.positionY < 0 || this.positionY > window.innerHeight - this.powerupBitmap.image.height) speedY = -speedY;
        };

        this.isCollision = function (playerX, playerY, playerW, playerH) {
            var centerX = this.positionX + (this.powerupBitmap.image.width * scaleW / 2);
            var centerY = this.positionY + (this.powerupBitmap.image.height * scaleH / 2);

            if ((centerX >= playerX - playerW / 2) && (centerX < playerX + playerW / 2)) {
                if ((centerY >= playerY - playerH / 2) && (centerY < playerY + playerH / 2)) {
                    return true;
                }
            }

            return false;
        }
        this.powerupBitmap = pfx;
    }

    function addnewdustandpowerup() {
        timeToAddNewDust = newdustfrequency;
        dusts.push(new Dust(new createjs.Bitmap(dustImage)));
        dusts[dusts.length - 1].setscale();
        dusts[dusts.length - 1].setStartPosition(player.positionX, player.positionY);
        dusts[dusts.length - 1].dustBitmap.visible = true;
        gameStage.addChild(dusts[dusts.length - 1].dustBitmap);

        if (havepowerup == false) {
            var random_powerup = Math.random();
            if (random_powerup < powerup_freeze_percent / 100) {
                powerup = new Powerup(new createjs.Bitmap(freezeImage));
                poweruptype = 1;
            }
            else if (random_powerup < ((powerup_freeze_percent + powerup_bomb_percent) / 100)) {
                powerup = new Powerup(new createjs.Bitmap(bombImage));
                poweruptype = 2;
            }
            else if (random_powerup < ((powerup_freeze_percent + powerup_bomb_percent + powerup_reverse_percent) / 100)) {
                powerup = new Powerup(new createjs.Bitmap(reverseImage));
                poweruptype = 3;
            }
            else if (random_powerup < ((powerup_freeze_percent + powerup_bomb_percent + powerup_reverse_percent + powerup_aimplayer_percent) / 100)) {
                powerup = new Powerup(new createjs.Bitmap(aimplayerImage));
                poweruptype = 4;
            }
            else if (random_powerup > ((100 - powerup_dustsmaller_percent) / 100)) {
                powerup = new Powerup(new createjs.Bitmap(dustsmallerImage));
                poweruptype = 5;
            }
            else if (random_powerup > ((100 - powerup_dustsmaller_percent - powerup_ufosmaller_percent) / 100)) {
                powerup = new Powerup(new createjs.Bitmap(ufosmallerImage));
                poweruptype = 6;
            }
            else poweruptype = 0;
            if (poweruptype > 0) {
                powerup.setscale();
                powerup.setStartPosition();
                gameStage.addChild(powerup.powerupBitmap);
                powerup.powerupBitmap.visible = true;
                havepowerup = true;
            }
        }
    }

    function powerup_collision() {
        if (powerupmode > 0) gameStage.removeChild(powerupicon);
        powerupmode = poweruptype;
        gameStage.removeChild(powerup.powerupBitmap);
        havepowerup = false;

        if (powerupmode == 1) powerupicon = new createjs.Bitmap(freezeImage);
        else if (powerupmode == 2) powerupicon = new createjs.Bitmap(bombImage);
        else if (powerupmode == 3) powerupicon = new createjs.Bitmap(reverseImage);
        else if (powerupmode == 4) powerupicon = new createjs.Bitmap(aimplayerImage);
        else if (powerupmode == 5) powerupicon = new createjs.Bitmap(dustsmallerImage);
        else if (powerupmode == 6) powerupicon = new createjs.Bitmap(ufosmallerImage);
        powerupicon.scaleX = scaleW * 1.5;
        powerupicon.scaleY = scaleH * 1.5;
        powerupicon.x = window.innerWidth - 3 * powerupicon.image.width;
        powerupicon.y = window.innerHeight - 3 * powerupicon.image.height;
        gameStage.addChild(powerupicon);
    }
    
    function update() {
        if (newGame) {
            logoScreenBitmap.visible = true;
            playerIdleBitmap.visible = false;
            spaceBitmap.visible = false;
            freezeperiod = false;
            poweruptime = 0;
            freezespeed = 1;
            addnewpowerup = true;
            havepowerup = false;
        } else {
            if (isGameOver) {
                isGameOver = false;
                addnewpowerup = false;
                dusts.length = 0;
                freezeText.visible = false;
                notaimText.visible = false;
                dustsmallerText.visible = false;
                ufosmallerText.visible = false;
                gameStage.clear();

                gameStage.addChild(logoScreenBitmap);
                gameStage.addChild(spaceBitmap);
                gameStage.addChild(playerIdleBitmap);
                gameStage.addChild(scoreText);
                gameStage.addChild(freezeText);
                gameStage.addChild(notaimText);
                gameStage.addChild(dustsmallerText);
                gameStage.addChild(ufosmallerText);
                newGame = true;

                gameStage.update();
            }
            else {
                scoreText.visible = true;
                logoScreenBitmap.visible = false;
                playerIdleBitmap.visible = true;
                spaceBitmap.visible = true;
                player.positionX = player.targetX;
                player.positionY = player.targetY;

                timeToAddNewDust -= 1 * freezespeed;
                if (timeToAddNewDust < 0) addnewdustandpowerup();

                countscore++;
                if (countscore >= 300) {
                    playerScore++;
                    countscore = 0;
                }

                if (playerScore < 0) playerScore = 0;
                scoreText.text = ("Score: " + playerScore);

                if (havepowerup) {
                    powerup.powerupBitmap.x = powerup.positionX;
                    powerup.powerupBitmap.y = powerup.positionY;
                    powerup.move();
                    if (powerup.isCollision(player.positionX, player.positionY, player.width, player.height)) powerup_collision();
                }

                if (freezeperiod) {
                    if (poweruptime > 0) {
                        freezeText.text = ("Freezing: " + Math.floor(poweruptime / 300));
                        poweruptime--;
                    }
                    else {
                        freezespeed *= 11;
                        freezeText.visible = false;
                        freezeperiod = false;
                    }
                }

                if (nownotaim) {
                    countdown = notaimplayer + notaimplayerperiod - dusts.length;
                    notaimText.text = ("No Diagonal: " + countdown);
                    if (countdown == 0) {
                        nownotaim = false;
                        notaimText.visible = false;
                    }
                }

                if (dustsmallerperiod) {
                    if (poweruptime2 > 0) {
                        dustsmallerText.text = ("Dust Small: " + Math.floor(poweruptime2 / 300));
                        poweruptime2--;
                    }
                    else {
                        dustpowerupsize = 1;
                        dustSpeed = dustSpeed / 1.5;
                        dustsmallerperiod = false;
                        dustsmallerText.visible = false;
                        for (var i = 0; i < dusts.length; i++) {
                            dusts[i].setscale();
                            dusts[i].setspeed(0.667);
                        }
                    }
                }

                if (ufosmallerperiod) {
                    if (poweruptime3 > 0) {
                        ufosmallerText.text = ("UFO Small: " + Math.floor(poweruptime3 / 300));
                        poweruptime3--;
                    }
                    else {
                        ufopowerupsize = 1;
                        ufosmallerperiod = false;
                        ufosmallerText.visible = false;
                        player.setscale();
                    }
                }

                for (var i = 0; i < dusts.length; i++) {
                    dusts[i].dustBitmap.x = dusts[i].positionX;
                    dusts[i].dustBitmap.y = dusts[i].positionY;
                    dusts[i].move();
                    if (dusts[i].positionX > window.innerWidth + dustImage.width || dusts[i].positionX < -dustImage.width || dusts[i].positionY > window.innerHeight + dustImage.height || dusts[i].positionY < -dustImage.height)
                        dusts[i].setStartPosition(player.positionX, player.positionY);
                    isGameOver = dusts[i].isCollision(player.positionX, player.positionY, player.width, player.height);
                    if (isGameOver) break;
                }

                playerIdleBitmap.x = player.positionX - (player.width * ufopowerupsize / 2);
                playerIdleBitmap.y = player.positionY - (player.height * ufopowerupsize / 2);
            }
        }
    }

    app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. You might use the
        // WinJS.Application.sessionState object, which is automatically
        // saved and restored across suspension. If you need to complete an
        // asynchronous operation before your application is suspended, call
        // args.setPromise().
    };
    
    document.addEventListener("DOMContentLoaded", initialize, false);
    
    app.start();
})();